package client.role;

import client.common.dto.AddRoleDto;
import client.common.result.Result;
import client.common.vo.PermissionVO;
import remote.service.PermissionService;
import remote.service.RoleService;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色添加窗口
 */
public class AddRoleForm extends JFrame {
    
    private JTextField nameField;
    private JTextArea descriptionArea;
    private JTable permissionTable;
    private PermissionTableModel permissionTableModel;
    private JButton submitButton;
    private JButton cancelButton;
    private JButton selectAllButton;
    private JButton deselectAllButton;
    
    private PermissionService permissionService = new PermissionService() {
    };
    private RoleService roleService = new RoleService() {
    };
    
    private RoleList roleListFrame; // 引入角色列表窗口，方便刷新
    
    public AddRoleForm(RoleList roleListFrame) {
        this.roleListFrame = roleListFrame;
        
        setTitle("添加角色");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null); // 居中
        
        initUI();
        loadPermissions(); // 加载权限列表
    }
    
    /**
     * 初始化界面组件
     */
    private void initUI() {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        
        // 上部表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        
        // 角色名称
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        formPanel.add(new JLabel("角色名称:"), gbc);
        
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        nameField = new JTextField(30);
        formPanel.add(nameField, gbc);
        
        // 角色描述
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.NONE;
        formPanel.add(new JLabel("角色描述:"), gbc);
        
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        descriptionArea = new JTextArea(5, 30);
        descriptionArea.setLineWrap(true);
        descriptionArea.setWrapStyleWord(true);
        JScrollPane descriptionScrollPane = new JScrollPane(descriptionArea);
        formPanel.add(descriptionScrollPane, gbc);
        
        // 权限列表
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.NONE;
        formPanel.add(new JLabel("选择权限:"), gbc);
        
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        permissionTableModel = new PermissionTableModel();
        permissionTable = new JTable(permissionTableModel) {
            // 使行高适合复选框
            @Override
            public Class getColumnClass(int column) {
                if (column == 0) {
                    return Boolean.class;
                }
                return String.class;
            }
        };
        permissionTable.setFillsViewportHeight(true);
        permissionTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane permissionScrollPane = new JScrollPane(permissionTable);
        formPanel.add(permissionScrollPane, gbc);
        
        // 全选和取消全选按钮
        JPanel selectPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        selectAllButton = new JButton("全选");
        deselectAllButton = new JButton("取消全选");
        selectPanel.add(selectAllButton);
        selectPanel.add(deselectAllButton);
        formPanel.add(selectPanel, gbc);
        
        mainPanel.add(formPanel, BorderLayout.CENTER);
        
        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        submitButton = new JButton("提交");
        cancelButton = new JButton("取消");
        buttonPanel.add(submitButton);
        buttonPanel.add(cancelButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        add(mainPanel);
        
        // 按钮事件
        submitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                submitRole();
            }
        });
        
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        
        // 全选按钮事件
        selectAllButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                permissionTableModel.selectAll();
            }
        });
        
        // 取消全选按钮事件
        deselectAllButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                permissionTableModel.deselectAll();
            }
        });
    }
    
    /**
     * 加载权限列表
     */
    private void loadPermissions() {
        SwingWorker<Result<List<PermissionVO>>, Void> worker = new SwingWorker<Result<List<PermissionVO>>, Void>() {
            @Override
            protected Result<List<PermissionVO>> doInBackground() throws Exception {
                return permissionService.getPermissionList();
            }
            
            @Override
            protected void done() {
                try {
                    Result<List<PermissionVO>> result = get();
                    if (result.getCode() == 200) {
                        List<PermissionVO> permissions = result.getData();
                        permissionTableModel.setPermissions(permissions);
                    } else if (result.getCode() == 403) {
                        JOptionPane.showMessageDialog(AddRoleForm.this, result.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                        dispose();
                    } else {
                        JOptionPane.showMessageDialog(AddRoleForm.this, "加载权限失败: " + result.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(AddRoleForm.this, "加载权限异常: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        worker.execute();
    }
    
    /**
     * 提交角色数据
     */
    private void submitRole() {
        String roleName = nameField.getText().trim();
        String roleDescription = descriptionArea.getText().trim();
        List<PermissionVO> selectedPermissions = permissionTableModel.getSelectedPermissions();
        
        if (roleName.isEmpty()) {
            JOptionPane.showMessageDialog(this, "角色名称不能为空。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        if (selectedPermissions.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请选择至少一个权限。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 拼接权限ID
        StringBuilder permissionIdsBuilder = new StringBuilder();
        for (int i = 0; i < selectedPermissions.size(); i++) {
            permissionIdsBuilder.append(selectedPermissions.get(i).getId());
            if (i < selectedPermissions.size() - 1) {
                permissionIdsBuilder.append(",");
            }
        }
        String permissionIdsStr = permissionIdsBuilder.toString();
        
        AddRoleDto addRoleDto = new AddRoleDto(roleName, roleDescription, permissionIdsStr);
        
        // 使用SwingWorker发送POST请求，避免阻塞UI
        SwingWorker<Result<String>, Void> worker = new SwingWorker<Result<String>, Void>() {
            @Override
            protected Result<String> doInBackground() throws Exception {
                return roleService.addRole(addRoleDto);
            }
            
            @Override
            protected void done() {
                try {
                    Result<String> result = get();
                    if (result.getCode() == 200) {
                        JOptionPane.showMessageDialog(AddRoleForm.this, "角色添加成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                        // 关闭窗口并刷新角色列表
                        dispose();
                        roleListFrame.refreshRoleList();  // 刷新角色列表
                    } else {
                        JOptionPane.showMessageDialog(AddRoleForm.this, "角色添加失败: " + result.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(AddRoleForm.this, "角色添加异常: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        worker.execute();
    }
    
    /**
     * 权限表格模型
     */
    class PermissionTableModel extends AbstractTableModel {
        
        private final String[] columnNames = {"选择", "ID", "描述"};
        private List<PermissionVO> permissions;
        
        public void setPermissions(List<PermissionVO> permissions) {
            this.permissions = permissions;
            // 初始化所有权限的选中状态为false
            for (PermissionVO p : this.permissions) {
                p.setSelected(false);
            }
            fireTableDataChanged();
        }
        
        @Override
        public int getRowCount() {
            return permissions == null ? 0 : permissions.size();
        }
        
        @Override
        public int getColumnCount() {
            return columnNames.length;
        }
        
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            if (columnIndex == 0) {
                return Boolean.class;
            } else if (columnIndex == 1) {
                return Integer.class;
            }
            return String.class;
        }
        
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return columnIndex == 0; // 仅复选框列可编辑
        }
        
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            if (permissions == null || rowIndex >= permissions.size()) {
                return null;
            }
            PermissionVO permission = permissions.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return permission.getSelected();
                case 1:
                    return permission.getId();
                case 2:
                    return permission.getDescription();
                default:
                    return null;
            }
        }
        
        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            if (permissions == null || rowIndex >= permissions.size()) {
                return;
            }
            PermissionVO permission = permissions.get(rowIndex);
            if (columnIndex == 0 && aValue instanceof Boolean) {
                permission.setSelected((Boolean) aValue);
                fireTableCellUpdated(rowIndex, columnIndex);
            }
        }
        
        /**
         * 获取选中的权限
         */
        public List<PermissionVO> getSelectedPermissions() {
            List<PermissionVO> selected = new ArrayList<>();
            for (PermissionVO p : permissions) {
                if (p.getSelected()) {
                    selected.add(p);
                }
            }
            return selected;
        }
        
        /**
         * 全选权限
         */
        public void selectAll() {
            if (permissions != null) {
                for (PermissionVO p : permissions) {
                    p.setSelected(true);
                }
                fireTableDataChanged();
            }
        }
        
        /**
         * 取消全选权限
         */
        public void deselectAll() {
            if (permissions != null) {
                for (PermissionVO p : permissions) {
                    p.setSelected(false);
                }
                fireTableDataChanged();
            }
        }
    }
}
